package com.ruoyi.system.utils;

import com.ruoyi.common.config.RuoYiConfig;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.rendering.PDFRenderer;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;

public class PdfUtil {

    public static List<String> convertPDFToImages(PDDocument document) throws IOException {

        LocalDate localDate = LocalDate.now();
        String outputDir = RuoYiConfig.getComparePath() + "\\" + localDate.getYear() + "\\" + localDate.getMonth() + "\\" + localDate.getDayOfMonth();

        File file = new File(outputDir);
        if (!file.exists()) {
            file.mkdirs();
        }

        List<String> strings = new ArrayList<>();
        PDFRenderer renderer = new PDFRenderer(document);
        for (int page = 0; page < document.getNumberOfPages(); ++page) {
            double random = Math.random();
            BufferedImage img = renderer.renderImageWithDPI(page, 720);
            ImageIO.write(img, "JPEG", new File(outputDir + "/page_" + random + ".jpg"));
            strings.add(outputDir + "/page_" + random + "" + ".jpg");
        }
        return strings;
    }

}
